<template>
  <div class="orders-page">
    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.order_id" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="店铺名称">
          <el-input v-model="searchForm.shop_name" placeholder="请输入店铺名称" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.product_name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.order_status" placeholder="请选择状态" clearable>
            <el-option label="已完成" value="已完成" />
            <el-option label="待发货" value="待发货" />
            <el-option label="已发货" value="已发货" />
            <el-option label="已取消" value="已取消" />
            <el-option label="已退款" value="已退款" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <div class="action-buttons">
        <el-button type="primary" @click="handleSync">
          <el-icon><Refresh /></el-icon>
          同步订单
        </el-button>
        <el-button type="success" @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入订单
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出订单
        </el-button>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <el-table :data="orderList" style="width: 100%" v-loading="loading" max-height="600">
        <el-table-column prop="shop_name" label="店铺名称" width="150" />
        <el-table-column prop="order_no" label="抖店订单号" width="180" />
        <el-table-column prop="goods_id" label="商品ID" width="120" />
        <el-table-column prop="product_name" label="商品名称" width="200" show-overflow-tooltip />
        <el-table-column prop="order_status_str" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.order_status_str)">
              {{ row.order_status_str }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="order_date" label="下单时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.order_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="post_amount" label="运费" width="80">
          <template #default="{ row }">
            {{ formatMoney(row.post_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="insurance_amount" label="运费险" width="80">
          <template #default="{ row }">
            {{ formatMoney(row.insurance_amount || 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="commission_price" label="服务费" width="80">
          <template #default="{ row }">
            {{ formatMoney(row.commission_price) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="预收款金额" width="100">
          <template #default="{ row }">
            {{ formatMoney(row.total_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="pay_amount" label="实际收款金额" width="100">
          <template #default="{ row }">
            {{ formatMoney(row.pay_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="parent_order_id" label="外部订单号" width="150" />
        <el-table-column prop="pay_amount" label="付款金额" width="100">
          <template #default="{ row }">
            {{ formatMoney(row.pay_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="profit" label="预计利润" width="100">
          <template #default="{ row }">
            <span :class="{ 'profit-positive': row.profit > 0, 'profit-negative': row.profit < 0 }">
              {{ formatMoney(row.profit) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="actual_profit" label="实际利润" width="100">
          <template #default="{ row }">
            <span :class="{ 'profit-positive': row.actual_profit > 0, 'profit-negative': row.actual_profit < 0 }">
              {{ formatMoney(row.actual_profit || row.profit) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { useApi } from '@/composables/useApi'

// 搜索表单
const searchForm = reactive({
  order_id: '',
  shop_name: '',
  product_name: '',
  order_status: '',
  date_range: []
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 加载状态
const loading = ref(false)

// 订单列表
const orderList = ref([])

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchOrders()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    order_id: '',
    shop_name: '',
    product_name: '',
    order_status: '',
    date_range: []
  })
  handleSearch()
}

// 同步订单
const handleSync = async () => {
  try {
    loading.value = true
    const response = await api.post('/api/orders/sync')
    
    if (response.code === 200) {
      ElMessage.success('同步任务已启动')
      fetchOrders()
    } else {
      ElMessage.error(response.message || '同步失败')
    }
  } catch (error) {
    console.error('同步失败:', error)
    ElMessage.error('同步失败')
  } finally {
    loading.value = false
  }
}

// 导入订单
const handleImport = () => {
  // TODO: 跳转到导入页面
}

// 导出订单
const handleExport = () => {
  // TODO: 调用导出API
  ElMessage.success('导出成功')
}

// 查看订单
const handleView = (row: any) => {
  // TODO: 跳转到订单详情页面
  console.log('查看订单:', row)
}

// 编辑订单
const handleEdit = (row: any) => {
  // TODO: 跳转到订单编辑页面
  console.log('编辑订单:', row)
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchOrders()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchOrders()
}

// API实例
const api = useApi()

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current,
      limit: pagination.size,
      order_id: searchForm.order_id,
      shop_name: searchForm.shop_name,
      product_name: searchForm.product_name,
      order_status: searchForm.order_status,
      date_range: searchForm.date_range
    }
    
    const response = await api.get('/orders', { params })
    
    if (response.code === 200) {
      orderList.value = response.data.list
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化金额
const formatMoney = (amount: number) => {
  return `¥${amount.toFixed(2)}`
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '已完成': 'success',
    '待发货': 'warning',
    '已发货': 'primary',
    '已取消': 'danger',
    '已退款': 'danger'
  }
  return statusMap[status] || 'info'
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.action-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.profit-positive {
  color: #67c23a;
}

.profit-negative {
  color: #f56c6c;
}
</style> 